package com.gao.exp03;

import com.gao.exp03.models.RegionStats;
import com.gao.exp03.models.StatisticsData;
import lombok.Data;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
@Data
public class DataService implements InitializingBean {
    public List<RegionStats> dataList = new ArrayList<RegionStats>();
    public StatisticsData statistics = new StatisticsData();


    @Scheduled(cron = " 0 0 1 * * * ")
    @Async
    public void GetData() throws IOException {
        RequestEntity<Void> requestEntity;
        requestEntity = RequestEntity
                .get(URI.create("https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"))
                .header("User-Agent", "Mozilla/5.0")
                .build();
        ResponseEntity<Resource> response = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = response.getBody();
        assert body != null;
        InputStream inputStream = body.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream);
        Reader in = new BufferedReader(reader);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);

        int index = 0;
        for (CSVRecord record : records) {
            if (index == 0) {
                statistics.setLatestDate(record.get(record.size() - 1));
                index++;
                continue;
            }
            RegionStats rs = new RegionStats();
            rs.setCountry(record.get(1));
            rs.setState(record.get(0));
            rs.setLatestTotalCases(Integer.parseInt(record.get(record.size() - 1)));
            rs.setDiffFromPrevDay(rs.getLatestTotalCases() - Integer.parseInt(record.get(record.size() - 2)));
            statistics.setLatestTotalCases(statistics.getLatestTotalCases() + rs.getLatestTotalCases());
            statistics.setDiffFromPrevDay(statistics.getDiffFromPrevDay() + rs.getDiffFromPrevDay());
            dataList.add(rs);
        }


    }


    @Override
    public void afterPropertiesSet() throws Exception {
        GetData();
    }
}
